using EasyXaf.LowCode.WorkflowEditors.Models;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;

namespace EasyXaf.LowCode.WorkflowEditors;

public partial class WorkflowNavigator : IAsyncDisposable
{
    private IJSObjectReference JsModule { get; set; }

    [Parameter]
    public string WorkflowEditorEleId { get; set; }

    [Parameter]
    public IContainer Container { get; set; }

    [Inject]
    private IJSRuntime JSRuntime { get; set; }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);

        if (firstRender)
        {
            var jsModuleFile = "./_content/EasyXaf.LowCode.WorkflowEditors/WorkflowNavigator.razor.js";
            JsModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import", jsModuleFile);
            await JsModule.InvokeVoidAsync("init", WorkflowEditorEleId);
        }
    }

    public async ValueTask DisposeAsync()
    {
        try
        {
            if (JsModule != null)
            {
                await JsModule.InvokeVoidAsync("dispose", WorkflowEditorEleId);
                await JsModule.DisposeAsync();
                JsModule = null;
            }
        }
        catch (JSDisconnectedException)
        {
        }

        GC.SuppressFinalize(this);
    }
}